<?php

namespace App\Service\Cruise\Archive;

use App\Enums\Cruise\CruiseEnum;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Library\Rms\RmsShopApi;
use App\Models\Common\ResourcesModel;
use App\Models\Cruise\CruiseShopAccountModel;
use App\Models\Cruise\FranchiseeArchiveModel;
use App\Models\OpenShop\Common\ShopArchiveModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserBaseInfoModel;
use Carbon\Carbon;

class ArchiveService
{
    const LICENSE_STATUS_NOT_FOUND = 1;//执照 -状态 1：缺失
    const LICENSE_STATUS_EXPIRE    = 2;//执照 -状态 2：过期
    const LICENSE_STATUS_DEFAULT   = 3;//执照 -状态 3: 正常

    public static function franchiseeUpdate($id, $params)
    {
        FranchiseeArchiveModel::query()
            ->where('id', $id)
            ->update($params);
    }

    public static function franchiseeDetail($shopId)
    {
        $cruiseModel = CruiseShopAccountModel::query()
            ->where('shopId', $shopId)
            ->with(['userIdentityCardRel', 'siteLocationRel', 'orderManagerRel', 'startBusinessRel', 'cruiseOrderRel', 'signOrderRel', 'franchiseeArchivesRel', 'userWorkExperienceRel'])
            ->first();
        $startRes    = CruiseEnum::NOT_OPEN_BUSINESS;   // 用于给前端判断是否显示
        if ($cruiseModel->startBusinessRel->count() && $cruiseModel->startBusinessRel[0]->startBusinessTime > 0 && $cruiseModel->startBusinessRel[0]->startBusinessTime < time()) {
            $startRes = CruiseEnum::OPEN_BUSINESS;   // 用于给前端判断是否显示
        }

        if ($cruiseModel->userIdentityCardRel->count()) {
            $name = $cruiseModel->userIdentityCardRel[0]->name ?: '-';
            $age  = (new Carbon($cruiseModel->userIdentityCardRel[0]->birthday))->diffInYears();
        } else {
            $name = '-';
            $age  = '-';
        }

        $orderNo           = '';
        $mainProcessId     = 0;
        $shopCount         = 0;
        $franchiseeArchive = [];
        $shopIds           = [];
        $shopStatusList    = [];
        $shopList          = [];
        if ($cruiseModel->signOrderRel->count()) {
            OpenShopSignOrderModel::query()
                ->whereIn('status', [SignOrderEnum::ORDER_STATUS_OK, SignOrderEnum::ORDER_STATUS_COMPLETE])
                ->where('merchantUserId', $cruiseModel->signOrderRel[0]->merchantUserId)
                ->with(['startBusinessRel', 'progressRel'])
                ->get()
                ->each(function (OpenShopSignOrderModel $openShopSignOrderQuery) use (&$shopIds, &$shopStatusList, &$shopCount) {
                    if (null != $openShopSignOrderQuery->progressRel) {
                        $shopIds[] = $openShopSignOrderQuery->progressRel->shopId;
                        if ($openShopSignOrderQuery->progressRel->shopId > 0) {
                            ++$shopCount;
                        }
                    }
                    if (null != $openShopSignOrderQuery->startBusinessRel && $openShopSignOrderQuery->startBusinessRel->startBusinessTime > 0 && $openShopSignOrderQuery->startBusinessRel->startBusinessTime < time()) {
                        $shopStatusList[(int)optional($openShopSignOrderQuery->progressRel)->shopId] = CruiseEnum::OPEN_BUSINESS;
                    } else {
                        $shopStatusList[(int)optional($openShopSignOrderQuery->progressRel)->shopId] = CruiseEnum::NOT_OPEN_BUSINESS;
                    }
                });
            $mainProcessId = $cruiseModel->signOrderRel[0]->mainProcessId;
            $orderNo       = $cruiseModel->signOrderRel[0]->orderNo;
        }
        $shopInfo = (new RmsShopApi())->getShopByIds($shopIds, ['id', 'shopCode', 'name'])['data']['shopList'] ?? [];
        foreach ($shopInfo as $shop) {
            $shopList[] = [
                'shopName'       => $shop['name'],
                'shopStatus'     => $shopStatusList[$shop['id']] ?? 0,
                'shopStatusText' => CruiseEnum::BUSINESS_STATUS_MAPPING[$shopStatusList[$shop['id']] ?? 0] ?? '-'
            ];
        }
        //加盟商档案
        if ($cruiseModel->franchiseeArchivesRel->count()) {
            //有数据取数据
            $franchiseeArchive = $cruiseModel->franchiseeArchivesRel[0]->toArray();
        } else {
            //无数据->聚合添加
            $userBaseInfoQuery                   = OpenShopUserBaseInfoModel::query()
                ->where('orderNo', $orderNo)
                ->first();
            $franchiseeArchive['mobile']         = $userBaseInfoQuery->mobile;
            $franchiseeArchive['remarkMobile1']  = $userBaseInfoQuery->remarkMobile1;
            $franchiseeArchive['remarkMobile2']  = $userBaseInfoQuery->remarkMobile2;
            $franchiseeArchive['isSelfManaged']  = $userBaseInfoQuery->isSelfManaged;
            $franchiseeArchive['shopBudget']     = $userBaseInfoQuery->shopBudget;
            $franchiseeArchive['investmentMode'] = $userBaseInfoQuery->investmentMode;
            $franchiseeArchive['financeSource']  = $userBaseInfoQuery->financeSource;

            if ($cruiseModel->userWorkExperienceRel->count()) {
                $franchiseeArchive['cateringExperience']   = $cruiseModel->userWorkExperienceRel[0]->cateringExperience;
                $franchiseeArchive['joinChainExperience']  = $cruiseModel->userWorkExperienceRel[0]->joinChainExperience;
                $franchiseeArchive['employmentExperience'] = $cruiseModel->userWorkExperienceRel[0]->employmentExperience;
                $franchiseeArchive['workLife']             = $cruiseModel->userWorkExperienceRel[0]->workLife;
            }
            $franchiseeArchive['educationalBackground'] = 0;
            $franchiseeArchive['occupationBackground']  = '';
            $franchiseeArchive['mainProcessId']         = $mainProcessId;
            $franchiseeArchiveModel                     = FranchiseeArchiveModel::create($franchiseeArchive);
            $franchiseeArchive['id']                    = $franchiseeArchiveModel->id;
        }
        $franchiseeArchive['name']           = $name;
        $franchiseeArchive['age']            = $age;
        $franchiseeArchive['shopCount']      = $shopCount;
        $franchiseeArchive['shopStatus']     = $startRes;
        $franchiseeArchive['shopStatusText'] = CruiseEnum::BUSINESS_STATUS_MAPPING[$startRes] ?? '-';
        $franchiseeArchive['shopList']       = $shopList;
        return $franchiseeArchive;
    }


    /**
     * 查询 门店档案-营业执照和许可证 详情
     * @param $shopId
     * @param int $flagStatus 1-只获取证照状态
     * @return array
     */
    public static function shopArchiveDetail($shopId, $flagStatus = 0): array
    {
        $info = ShopArchiveModel::getInfoByShopId($shopId);
        if (!$info) {
            return [
                'businessLicenseStatus'     => self::LICENSE_STATUS_NOT_FOUND,//营业执照 -状态 1：缺失2：过期3:正常
                'foodBusinessLicenseStatus' => self::LICENSE_STATUS_NOT_FOUND,//食品经营许可证 -状态 1：缺失2：过期3:正常
            ];
        }
        $time = time();
        $data = [
            'businessLicenseStatus'     => strtotime($info['businessLicenseEndDate']) > $time ? self::LICENSE_STATUS_DEFAULT :
                ($info['businessLicenseEndDate'] == '0000-00-00' || !$info['businessLicense'] ? self::LICENSE_STATUS_NOT_FOUND : self::LICENSE_STATUS_EXPIRE),//营业执照 -状态 1：缺失2：过期3:正常
            'foodBusinessLicenseStatus' => strtotime($info['foodBusinessLicenseEndDate']) > $time ? self::LICENSE_STATUS_DEFAULT :
                ($info['foodBusinessLicenseEndDate'] == '0000-00-00' || !$info['foodBusinessLicense'] ? self::LICENSE_STATUS_NOT_FOUND : self::LICENSE_STATUS_EXPIRE),//食品经营许可证 -状态 1：缺失2：过期3:正常
        ];
        if ($flagStatus == 1) {//返回证照状态
            return $data;
        }
        $businessLicenseUrl = $foodBusinessLicenseUrl = '';
        collect($info->resourcesRel)->each(
            function (ResourcesModel $resourcesModel) use (&$businessLicenseUrl, &$foodBusinessLicenseUrl) {
                if ($resourcesModel->name == ShopArchiveModel::RESOURCE_BUSINESS_IMG) {  //营业执照
                    $businessLicenseUrl = picturePath($resourcesModel->url ?? "");
                } elseif ($resourcesModel->name == ShopArchiveModel::RESOURCE_FOOD_BUSINESS_IMG) {
                    $foodBusinessLicenseUrl = picturePath($resourcesModel->url ?? "");
                }
            }
        )->toArray();
        return array_merge(
            [
                'businessLicense'              => $info['businessLicense'] ?? "",                                                                                                             //营业执照 - 经营范围
                'businessLicenseStartDate'     => $info['businessLicenseStartDate'] && $info['businessLicenseStartDate'] != '0000-00-00' ? $info['businessLicenseStartDate'] : "",            //营业执照 - 发证日期
                'businessLicenseEndDate'       => $info['businessLicenseEndDate'] && $info['businessLicenseEndDate'] != '0000-00-00' ? $info['businessLicenseEndDate'] : "",                  //营业执照 - 到期日期
                'businessLicenseUrl'           => $businessLicenseUrl,                                                                                                                        //营业执照 -url
                'foodBusinessLicense'          => $info['foodBusinessLicense'] ?? "",                                                                                                         //食品经营许可证 - 经营范围
                'foodBusinessLicenseStartDate' => $info['foodBusinessLicenseStartDate'] && $info['foodBusinessLicenseStartDate'] != '0000-00-00' ? $info['foodBusinessLicenseStartDate'] : "",//食品经营许可证 - 发证日期
                'foodBusinessLicenseEndDate'   => $info['foodBusinessLicenseEndDate'] && $info['foodBusinessLicenseEndDate'] != '0000-00-00' ? $info['foodBusinessLicenseEndDate'] : "",      //食品经营许可证 - 到期日期
                'foodBusinessLicenseUrl'       => $foodBusinessLicenseUrl,                                                                                                                    //食品经营许可证 -url
            ], $data
        );
    }


    /**
     * 修改 门店档案-营业执照和许可证
     * @param $shopId
     * @param $data
     */
    public static function shopArchiveUpdate($shopId, $data)
    {
        $info       = ShopArchiveModel::getInfoByShopId($shopId);
        $updateData = [
            'shopId'                       => $shopId,
            'businessLicense'              => $data['businessLicense'],             //营业执照 - 经营范围
            'businessLicenseStartDate'     => $data['businessLicenseStartDate'],    //营业执照 - 发证日期
            'businessLicenseEndDate'       => $data['businessLicenseEndDate'],      //营业执照 - 到期日期（永久：9999-12-13）
            'foodBusinessLicense'          => $data['foodBusinessLicense'],         //食品经营许可证 - 经营范围
            'foodBusinessLicenseStartDate' => $data['foodBusinessLicenseStartDate'],//食品经营许可证 - 发证日期
            'foodBusinessLicenseEndDate'   => $data['foodBusinessLicenseEndDate'],  //食品经营许可证 - 到期日期（永久：9999-12-13）
        ];
        if (!$info) {
            $updateData['shopId'] = $shopId;
            $res                  = ShopArchiveModel::addShopArchive($updateData);
            $info['id']           = $res->id;
        } else {
            ShopArchiveModel::setShopArchiveById($info['id'], $updateData);
        }
        $businessLicenseImg     = ltrim(parse_url($data['businessLicenseUrl'], PHP_URL_PATH), '/');
        $foodBusinessLicenseImg = ltrim(parse_url($data['foodBusinessLicenseUrl'], PHP_URL_PATH), '/');
        $resources              = [
            'businessLicenseImg'     => $businessLicenseImg,
            'foodBusinessLicenseImg' => $foodBusinessLicenseImg,
        ];
        //保存资源
        ResourcesModel::moduleBusinessResourcesUpdate(
            $resources,
            ResourcesModel::MODULE_TYPE_SHOP,
            ResourcesModel::BUSINESS_SHOP_ARCHIVE,
            (int)$info['id'],
        );
    }
}
